package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class RegisterController {

    @Autowired
    private IKaptchaService kaptchaService;

    @Autowired
    private IUserRegisterService registerService;

    @PostMapping("register")
    public ResponseData<Object> register(@RequestBody @Validated UserRegisterRequest reg,
        HttpServletRequest request) {
        // 验证输入验证码
        String captcha = reg.getCaptcha();
        // 获取uuid
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        // 为验证码request对象设置值
        KaptchaCodeRequest codeRequest = new KaptchaCodeRequest();
        codeRequest.setCode(captcha);
        codeRequest.setUuid(uuid);
        // 如果验证码对不上会进入异常处理，不会进到下面的逻辑
        kaptchaService.validateKaptchaCode(codeRequest);
        // 进行注册业务逻辑
        registerService.register(reg);
        return new ResponseUtil<>().setData(null);
    }

    @GetMapping("verify")
    public ResponseData<Object> verify(@Validated UserVerifyRequest verifyReq) {
        registerService.verify(verifyReq);
        return new ResponseUtil<>().setData(null);
    }
}
